package fr.greta.centreFormation.controller;

import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.greta.centreFormation.bean.Domaine;
import fr.greta.centreFormation.bean.Info;
import fr.greta.centreFormation.dao.Bdd;
import fr.greta.centreFormation.dao.DomaineHome;
import fr.greta.centreFormation.dao.InfoHome;

/**
 * Servlet implementation class ScriptModifInfo
 */
public class ScriptModifInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ScriptModifInfo() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		////----------------------------------\\\\
		///		V�rification des donn�es	   \\\
		//--------------------------------------\\

		String dateS = request.getParameter("dateInfo");
		java.util.Date dateD = null;

		if(dateS != null){

			System.out.println(dateS);
			SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");

			try {
				dateD = formatDate.parse(dateS);
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}

		String titre = request.getParameter("titre");
		String contenu = request.getParameter("contenu");

		HttpSession session = request.getSession(true);

		if(titre == "" || contenu == ""){

			System.out.println("manque donner");

			Info uneInfo = new Info();
			uneInfo.setDateInfo(dateD);
			uneInfo.setContenuInfo(contenu);
			uneInfo.setIntituleInfo(titre);

			session.setAttribute("uneInfo", uneInfo);
			session.setAttribute("etat", "Certain champs n'ont pas �t� remplis.");

			request.getRequestDispatcher("formulaireInfo.jsp").forward(request, response);

		}else{

			////----------------------------------\\\\
			///		Insertion dans la base		   \\\
			//--------------------------------------\\

			Bdd connection =  new Bdd();
			Info uneInfo = new Info();

			uneInfo.setIdInfo((Integer) session.getAttribute("idInfo"));

			uneInfo.setDateInfo(dateD);
			uneInfo.setContenuInfo(contenu);
			uneInfo.setIntituleInfo(titre);

			System.out.println("resultat update => "+InfoHome.updateInfo(uneInfo));

			response.sendRedirect("ModifInfo");
			//request.getRequestDispatcher("ModifInfo").forward(request, response);


		}


	}

}
